
import api from "./api.js";

export default (data={}) => {
    return new Promise((resolve,reject) => {
        let header = {}
        // 获取token
        if(uni.getStorageSync('token')) header["Authorization"] =  uni.getStorageSync('token');
        let method = "post";  // 默认 post 请求
        if(data.method) method = data.method;
        
        uni.request({
            // url: api.base_url + data.url, 
            url: data.url, 
            data: data.data,
            method,
            header,
            sslVerify: false,
            timeout: 5000,
            success(res) {
                let code = res.data.code;
                if(code == 10002) {
                    errHint('没有访问权限')
                    return
                }
                if(code == 10003) {
                    errHint('登陆已过期')
                    return
                }
                if(code == 10005) {
                    uni.showToast({
                        title:"异常",
                        icon: "none",
                    });
                    return
                }
                resolve(res.data)
            },
            fail(err) {
                console.log('请求异常',err)
                if(err.errMsg == "request:fail timeout") {
                    uni.showToast({
                        title:"请求超时",
                        icon: "none",
                    });
                }else {
                    uni.showToast({
                        title:"请求异常",
                        icon: "none",
                    });
                }
                reject(err)
            }
        });


        // 错误提示
        let errHint = (title) => {
            uni.removeStorage({
                key: 'token',
                success(res) {
                    uni.showToast({
                        title,
                        icon: "none",
                    });
                    setTimeout(() => {
                        uni.reLaunch({
                            url: '/pages/login/login'
                        });
                    },2000)
                }
            });
        }
    })
    
}